
//stringbuffer类
function StringBuffer() {
	  this.__strings__ = [];
};
StringBuffer.prototype.append = function(str) {
  this.__strings__.push(str);
};
StringBuffer.prototype.toString = function() {
  return this.__strings__.join('');
};

//引入js和css文件
function include(id, path, file){
	if (document.getElementById(id)==null){
        var files = typeof file == "string" ? [file] : file;
        for (var i = 0; i < files.length; i++){
            var name = files[i].replace(/^\s|\s$/g, "");
            var att = name.split('.');
            var ext = att[att.length - 1].toLowerCase();
            var isCSS = ext == "css";
            var tag = isCSS ? "link" : "script";
            var attr = isCSS ? " type='text/css' rel='stylesheet' " : " type='text/javascript' ";
            var link = (isCSS ? "href" : "src") + "='" + path + name + "'";
            document.write("<" + tag + (i==0?" id="+id:"") + attr + link + "></" + tag + ">");
        }
	}
}

//获取URL地址参数
function getQueryString(name, url) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    if (!url || url == ""){
	    url = window.location.search;
    }else{	
    	url = url.substring(url.indexOf("?"));
    }
    r = url.substr(1).match(reg)
    if (r != null) return unescape(r[2]); return null;
}

//获取字典标签
function getDictLabel(data, value, defaultValue){
	for (var i=0; i<data.length; i++){
		var row = data[i];
		if (row.value == value){
			return row.label;
		}
	}
	return defaultValue;
}

//ctx：是canvas的上下文
//imgBack：星星的背景星星
//img：星星的前景星星
//acc：0-1的比例
//numberOfStar：星星的总个数
//dw：星星绘制出来的宽度
//dh：星星绘制出来的高度
function drawStar(ctx, imgBack, img, acc, numberOfStar, dw, dh){
	var score = acc * numberOfStar;				//将比率转换为基于星星总数的得分
	
	for(var i = 0; i < numberOfStar; ++i){
		//画背景
		ctx.drawImage(imgBack, 0, 0, imgBack.width, imgBack.height, i * (dw+1), 0, dw, dh);
		
		//i必须小于score才执行
		if(i < score){
			if(i < score - 1){		// 4.8   4
				//..绘制整个星星
				ctx.drawImage(img, 0, 0, img.width, img.height, i * (dw+1), 0, dw, dh);
			}else{
				var remain = score - i;
				//画最后一段
				ctx.drawImage(img, 0, 0, img.width*remain, img.height, i * (dw+1), 0, dw*remain, dh);
			}
		}
	}
}

function preLoadImage(url, callback){
	var img = new Image();		
	img.src = url;
	
	if(img.complete){		//如果载入完成，表示是载入的缓存图片
		callback(img);
	}else{	//如果没有载入完成，表示是第一次加载
		
		//监听onload事件，并回调
		img.onload = function(){
			callback(this);
		}
	}
}

/**
 * 顺序载入多个图片完成
 * urls:多个图片的src
 * callback:执行绘制img的方法
 */
function preloadImages(urls, callback){
	var imgs = new Array(urls.length);
	var isCall = false;
	for(var i = 0; i < urls.length; ++i){
		imgs[i] = new Image();
		imgs[i].src = urls[i];
		imgs[i].onload = function(){
			var isFinish = true;  //图片已经加载完毕
			for(var k = 0;  k < urls.length; ++k){
				if(!imgs[k].complete){  //图片未加载
					isFinish = false;
					break;
				}
			}

			if(isFinish && !isCall){
				isCall = true;  //控制异步进行
				callback(imgs);
			}
		};
	}
}

//转向一个url
function toURL(url){
	window.location=url;
}

//打开一个url
function openURL(url){
	window.open(url);
}

//讲回复的json数据转换为对象
function respData(data){
	return eval("(" + data + ")");
}

function ajaxPost(url, data, success){
	$.ajax({
		url:url,
		data:data,
		type:"POST",
		dataType: "json",
		success:function(d){
			if(success != null) success(d);
		},
		error:function(d){
			tipErr(d);
		}
	});
}

function ajaxAsyncPost(url, data, success){
	$.ajax({
		url:url,
		data:data,
		async:false,
		type:"POST",
		dataType: "json",
		success:function(d){
			if(success != null) success(d);
		},
		error:function(d){
			tipErr(d);
		}
	});
}

function obj2json(obj){
	return JSON.stringify(obj);
}

//打开一个窗体
function windowOpen(url, name, width, height){
	var top=parseInt((window.screen.height-height)/2,10),left=parseInt((window.screen.width-width)/2,10),
		options="location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,"+
		"resizable=yes,scrollbars=yes,"+"width="+width+",height="+height+",top="+top+",left="+left;
	window.open(url ,name , options);
}

// 恢复提示框显示
function resetTip(){
	top.$.jBox.tip.mess = null;
}

// 关闭提示框
function closeTip(){
	top.$.jBox.closeTip();
}

//显示提示框
function showTip(mess, type, timeout, lazytime){
	resetTip();
	setTimeout(function(){
		top.$.jBox.tip(mess, (type == undefined || type == '' ? 'info' : type), {opacity:0, 
			timeout:  timeout == undefined ? 2000 : timeout});
	}, lazytime == undefined ? 500 : lazytime);
}

// 显示加载框
function loading(mess){
	if (mess == undefined || mess == ""){
		mess = "正在提交，请稍等...";
	}
	resetTip();
	top.$.jBox.tip(mess,'loading',{opacity:0});
}

// 关闭提示框
function closeLoading(){
	// 恢复提示框显示
	resetTip();
	// 关闭提示框
	closeTip();
}

// 警告对话框
function alertx(mess, closed){
	top.$.jBox.info(mess, '提示', {closed:function(){
		if (typeof closed == 'function') {
			closed();
		}
	}});
	top.$('.jbox-body .jbox-icon').css('top','55px');
}

// 确认对话框
function confirmx(mess, href, closed){
	top.$.jBox.confirm(mess,'系统提示',function(v,h,f){
		if(v=='ok'){
			if (typeof href == 'function') {
				href();
			}else{
				resetTip(); //loading();
				location = href;
			}
		}
	},{buttonsFocus:1, closed:function(){
		if (typeof closed == 'function') {
			closed();
		}
	}});
	top.$('.jbox-body .jbox-icon').css('top','55px');
	return false;
}

// 提示输入对话框
function promptx(title, lable, href, closed){
	top.$.jBox("<div class='form-search' style='padding:20px;text-align:center;'>" + lable + "：<input type='text' id='txt' name='txt'/></div>", {
			title: title, submit: function (v, h, f){
	    if (f.txt == '') {
	        top.$.jBox.tip("请输入" + lable + "。", 'error');
	        return false;
	    }
		if (typeof href == 'function') {
			href();
		}else{
			resetTip(); //loading();
			location = href + encodeURIComponent(f.txt);
		}
	},closed:function(){
		if (typeof closed == 'function') {
			closed();
		}
	}});
	return false;
}

//获取类的id，如果木有这个类，返回-1
function getClassID(cls, searchKey){
	//例如，portrait-img-0  返回0，如果没有这个，返回-1
	if(searchKey == null || cls == null) return -1;
	var p = cls.indexOf(searchKey);
	if(p == -1) return -1;
	p = p + searchKey.length;
	
	var n = cls.indexOf(" ", p);
	if(n == -1) n = cls.length;
	return parseInt(cls.substring(p, n));
}

//获取类的尺寸，没有返回null
function getClassSize(cls, searchKey){
	//例如，portrait-img-100x300  返回{w:100, h:300}，如果没有这个，返回null
	if(searchKey == null || cls == null) return -1;
	var p = cls.indexOf(searchKey);
	if(p == -1 || (p > 0 && cls.charAt(p-1) != " ")) return null;
	p = p + searchKey.length;
	
	var n = cls.indexOf(" ", p);
	if(n == -1) n = cls.length;
	var size = cls.substring(p, n).split("x");
	if(size.length != 2) return null;
	return {w: size[0], h: size[1]};
}

function onimageError(){
	var ctl = $(event.target);
	var cls = ctl.attr("class");
	var ndx;
	
	ctl[0].onerror = null;
	
	//处理头像的
	if((ndx = getClassID(cls, "portrait-img-")) != -1){
		ctl[0].src="/img/user/0/" + ndx;
	}else if((ndx = getClassID(cls, "portrait-img-")) != -1){
		ctl[0].src="/img/user/0/" + ndx;
	}else if((ndx = getClassSize(cls, "recproduct-img-")) != null){
		ctl[0].src="/img/recproduct/default/" + ndx.w + "x" + ndx.h;
	}else if((ndx = getClassSize(cls, "portrait-img-")) != null){
		ctl[0].src="/img/user/0/" + ndx.w + "x" + ndx.h + "/g";
	}
}

//实现js的replaceAll功能
String.prototype.replaceAll  = function(s1,s2){  
	return this.replace(new RegExp(s1,"gm"),s2);   //这里的gm是固定的，g可能表示global，m可能表示multiple。
	};

//用于格式化文本 日记中的问题部分
function toHtml2(txt){
	if (txt == null){
		return "";
	}
	return txt.replaceAll("\r\n","<br/>").replaceAll("\t","&nbsp; &nbsp; ");
}

//格式化时间   用法 /* var time2 = new Date().Format("yyyy-MM-dd hh:mm:ss");   */
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

function getURLHost(url){
	var p = /^(?:(\w+):\/\/)?(?:(\w+):?(\w+)?@)?([^:\/\?#]+)(?::(\d+))?(\/[^\?#]+)?(?:\?([^#]+))?(?:#(\w+))?/;
	//这是返回值  url = http://username:password@www.bbs0101.com:1234/artical/js/index.php?key1=js&key2=css#anchor
	/**
	[
    "http://username:password@www.bbs0101.com:1234/artical/js/index.php?key1=js&key2=css#anchor", 
    "http", 
    "username", 
    "password", 
    "www.bbs0101.com", 
    "1234", 
    "/artical/js/index.php", 
    "key1=js&key2=css", 
    "anchor"
	]
	 */
	return p.exec(url)[4];
}

function isInIOS(){
	var u = navigator.userAgent.toLowerCase();
	return u.indexOf('iphone') != -1 || u.indexOf('ipad') != -1;
}

function isInAndroid(){
	var u = navigator.userAgent.toLowerCase();
	return u.indexOf('android') != -1 || u.indexOf('linux') != -1;
}

function isInWechat(){
	var u = navigator.userAgent.toLowerCase();
	return u.indexOf('micromessenger') != -1;
}